package edu.ustb.efws.security;

import java.util.Optional;

/**
 * 用户认证工具类
 *
 * @author TS Group
 */
public class CredentialContextUtils {
    private static final ThreadLocal<Credential> threadLocal = new ThreadLocal<>();

    /**
     * 设置用户认证信息
     *
     * @param credential {@link Credential}
     */
    public static void setCredential(Credential credential){
        threadLocal.set(credential);
    }

    /**
     * 获取用户认证信息
     *
     * @return {@link Credential}
     */
    public static Optional<Credential> getCredentialOpt(){
        return Optional.ofNullable(threadLocal.get());
    }

    /**
     * 获取用户认证信息
     *
     * @return {@link Credential}
     */
    public static Credential getCredential(){
        Credential t = threadLocal.get();
        if(t == null){
            throw new SecException(110, "认证不存在");
        }
        return t;
    }
}
